package com.camel.record.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.camel.core.enums.YesNo;
import com.camel.record.model.*;
import com.camel.record.service.WebServerService;
import com.camel.record.service.ZsAnswerService;
import com.camel.record.service.ZsCdrinfoService;
import com.camel.record.service.ZsSeatService;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author Administrator
 */
@Service
public class WebServerServiceImpl implements WebServerService {

    @Resource
    private ZsCdrinfoService zsCdrinfoService;

    @Resource
    private CdrRecordServiceImpl cdrRecordService;

    @Resource
    private ZsSeatService zsSeatService;

    @Resource
    private CtiTaskServiceImpl taskService;

    @Resource
    private ZsAnswerService answerService;

    public static final SimpleDateFormat SIMPLEDATEFORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void saveCdr(Map<String, ZsCdrinfo[]> cdrInfos) {
        // 保存CDR报文 备查
        cdrRecordService.save(new CdrRecord(JSONObject.toJSONString(cdrInfos)));
        ZsCdrinfo[] cdrs = cdrInfos.get("cdr");

        if (ArrayUtils.isEmpty(cdrs)) {
            return;
        }
        for (ZsCdrinfo cdr : cdrs) {
            if (cdr.isNotValidData()) {
                System.err.println(cdr.getCallee_num() + "InValid： CallTime is Enpty Or Record File is Blank");
                continue;
            }
            // 是否保存过
            if (isSaved(cdr)) {
                System.err.println("The record has been saved ");
                continue;
            }

            // 提供坐席号 查询当前使用的人
            if (StringUtils.isNotBlank(cdr.getCaller_agent_num())) {
                QueryWrapper<ZsSeat> wrapper = new QueryWrapper<ZsSeat>().eq("state", YesNo.YES.getValue());
                wrapper.eq("agentnum", cdr.getCaller_agent_num());
                ZsSeat seat = zsSeatService.getOne(wrapper, false);
                cdr.setUid(seat.getUid());
            }

            // 提供外呼计划名称 获取外呼计划对应的问卷
            if (!ObjectUtils.isEmpty(cdr.getTaskname())) {
                CtiTask task = taskService.getOne(new QueryWrapper<CtiTask>().eq("taskid", cdr.getTaskname()), false);
                if(!ObjectUtils.isEmpty(task)) {
                    cdr.setSurveyId(task.getSurveyId());
                }
            }

            cdr.setId(UUID.randomUUID().toString());

            // 两种方式都未通过直接下一个
            // 通过call_uuid 确认答案
            if(!validAndUpdateByUuid(cdr)) {
                // 通过客户号码和问卷ID定位答案
                if(!ObjectUtils.isEmpty(cdr.getSurveyId()) && StringUtils.isNotBlank(cdr.getCallee_num())) {
                    validAndUpdateAnserByTaskAndPhone(cdr);
                }
            }
            System.out.println("Ready Save new Cdr Info");
            zsCdrinfoService.save(cdr);
        }


    }

    private boolean isSaved(ZsCdrinfo cdr) {
        QueryWrapper<ZsCdrinfo> cdrinfoWrapper = new QueryWrapper<>();
        cdrinfoWrapper.eq("call_uuid", cdr.getCall_uuid());
        return zsCdrinfoService.count(cdrinfoWrapper) > 0;
    }

    public boolean validAndUpdateByUuid(ZsCdrinfo cdr) {
        if(cdr.isNotValidData()) {
            return true;
        }
        if (org.springframework.util.StringUtils.isEmpty(cdr.getUuids())) {
            System.out.println("cdr 没有UUIDS");
        } else {
            String[] uuids = cdr.getUuids().split(",");
            List<ZsAnswer> zsAnswers = new ArrayList<>();
            for (String uuid : uuids) {
                List<ZsAnswer> tmpAnswers = answerService.list(new QueryWrapper<ZsAnswer>().eq("agent_uuid", uuid));
                if (!CollectionUtils.isEmpty(tmpAnswers)) {
                    zsAnswers = tmpAnswers;
                    cdr.setId(uuid);
                    break;
                }
            }
            if(!CollectionUtils.isEmpty(zsAnswers)) {
                for (ZsAnswer zsAnswer: zsAnswers) {
                    // 录音时长和录音都不为空则表示已有录音， 不做保存
                    if(StringUtils.isNotBlank(zsAnswer.getCallLastsTime()) && StringUtils.isNotBlank(zsAnswer.getRecord())) {
                        continue;
                    }
                    updateAnswer(zsAnswer.getId(), cdr);
                }
                return true;
            }
        }
        return false;
    }

    public void updateAnswer(Integer answerId, ZsCdrinfo cdrinfo) {
        if(ObjectUtils.isEmpty(answerId)) {
            return;
        }
        ZsAnswer answer = new ZsAnswer();
        answer.setId(answerId);
        answer.setAgentUUID(cdrinfo.getId());
        answer.setStartTime(cdrinfo.getStart_time());
        answer.setCallLastsTime(cdrinfo.getCall_lasts_time());
        answer.setRecord(cdrinfo.getRecordFile());
        answer.setTaskId(cdrinfo.getTaskid());
        try {
            answer.setEndTime(SIMPLEDATEFORMAT.format(SIMPLEDATEFORMAT.parse(answer.getStartTime()).getTime() + Long.parseLong(answer.getCallLastsTime()) * 1000));
            answerService.updateById(answer);
        }catch (ParseException e) {
            e.printStackTrace();
        }
    }

    public void validAndUpdateAnserByTaskAndPhone(ZsCdrinfo zsCdrinfo) {
        String taskname = zsCdrinfo.getTaskname();
        if(zsCdrinfo.isNotValidData()) {
            return;
        }
        if(StringUtils.isBlank(taskname)) {
            System.out.println("---------------------------taskname is null");
            return;
        }
        ZsAnswer answer = answerService.getOne(new QueryWrapper<ZsAnswer>().eq("survey_id", zsCdrinfo.getSurveyId()).eq("phone", zsCdrinfo.getCallee_num()));
        if(ObjectUtils.isEmpty(answer)) {
            System.out.println("----------------------------answer has been not found ");
            return;
        }
        // 当录音时长和录音文件都为空时 不保存
        if(StringUtils.isNotBlank(answer.getRecord()) && StringUtils.isNotBlank(answer.getCallLastsTime())) {
            return;
        }
        updateAnswer(answer.getId(), zsCdrinfo);
    }
}
